package org.jeecg.modules.extbpm.process.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.jeecg.common.api.dto.message.BusTemplateMessageDTO;
import org.jeecg.common.api.dto.message.TemplateDTO;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.jeecg.modules.extbpm.process.entity.ExtActTaskNotification;
import org.jeecg.modules.extbpm.process.mapper.ExtActTaskNotificationMapper;
import org.jeecg.modules.extbpm.process.service.IExtActTaskNotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.util.*;

/**
 * @Description: 流程催办
 * @Author: jeecg-boot
 * @Date:   2019-05-16
 * @Version: V1.0
 */
@Slf4j
@Service("extActTaskNotificationService")
public class ExtActTaskNotificationServiceImpl extends ServiceImpl<ExtActTaskNotificationMapper, ExtActTaskNotification> implements IExtActTaskNotificationService {

	@Autowired
	private TaskService taskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	protected IdentityService identityService;
	@Autowired
	private ExtActTaskNotificationMapper extActTaskNotificationMapper;
	@Value(value = "${spring.mail.username}")
	private String emailFrom;
	
	@Override
	@Transactional
	public void taskNotification(ExtActTaskNotification extActTaskNotification) {
		List<Task> taskList = taskService.createTaskQuery().active().processInstanceId(extActTaskNotification.getProcInstId()).list();
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(extActTaskNotification.getProcInstId()).singleResult();
		extActTaskNotification.setProcName(processInstance.getProcessDefinitionName());
		for(Task task:taskList){
			if(oConvertUtils.isNotEmpty(task.getAssignee())){
				log.info("--------发消息----------");
				extActTaskNotification.setId(UUIDGenerator.generate());
				extActTaskNotification.setTaskId(task.getId());
				extActTaskNotification.setTaskName(task.getName());
				extActTaskNotification.setTaskAssignee(task.getAssignee());
				extActTaskNotification.setOpTime(new Date());
				extActTaskNotification.setTaskAssignee(task.getAssignee());
				extActTaskNotificationMapper.insert(extActTaskNotification);
				String [] types = extActTaskNotification.getNotifyType().split(",");
				if(types!=null&&types.length>0) {
					List<String> list = Arrays.asList(types);
					//String subject = "流程【" + extActTaskNotification.getProcName()+ "】任务【" + extActTaskNotification.getTaskName()+ "】催办提醒";
					if(list.contains("2")) {
						log.info("--------邮件通知----------");
						LoginUser user = sysBaseAPI.getUserByName(task.getAssignee());
						if(user!=null&&user.getEmail()!=null) {
							try {
								JavaMailSender mailSender = (JavaMailSender) SpringContextUtils.getBean("mailSender");
								MimeMessage message = mailSender.createMimeMessage();
								MimeMessageHelper helper = new MimeMessageHelper(message,true);
								// 设置发送方邮箱地址
								helper.setFrom(emailFrom);
								helper.setTo(user.getEmail());
								helper.setSubject("流程催办提醒");
								Map<String, String> mp = new HashMap<>();
								mp.put("bpm_name",extActTaskNotification.getProcName());
								mp.put("bpm_task",extActTaskNotification.getTaskName());
								mp.put("remark",extActTaskNotification.getRemarks());
								mp.put("datetime",DateUtils.formatDateTime());
								TemplateDTO templateDTO = new TemplateDTO(CommonSendStatus.TZMB_BPM_CUIBAN,mp);
								String content = sysBaseAPI.parseTemplateByCode(templateDTO);
								helper.setText(content,true);
								mailSender.send(message);
							} catch (Exception e) {
								e.printStackTrace();
								log.error("--------邮件通知异常----------",e.getMessage());
							}
						}
					}
					if(list.contains("1")) {
						log.info("--------页面通知----------");
						//sysBaseAPI.sendSysAnnouncement(extActTaskNotification.getCreateBy(),extActTaskNotification.getTaskAssignee(),subject,extActTaskNotification.getRemarks());
						Map<String, String> mp = new HashMap<>();
						mp.put("bpm_name",extActTaskNotification.getProcName());
						mp.put("bpm_task",extActTaskNotification.getTaskName());
						mp.put("remark",extActTaskNotification.getRemarks());
						mp.put("datetime",DateUtils.formatDateTime());
						BusTemplateMessageDTO message = new BusTemplateMessageDTO(extActTaskNotification.getCreateBy(),extActTaskNotification.getTaskAssignee(),"流程催办提醒",mp, CommonSendStatus.TZMB_BPM_CUIBAN, SysAnnmentTypeEnum.BPM.getType(),processInstance.getId());
						sysBaseAPI.sendBusTemplateAnnouncement(message);
					}
				}
			}
		}
	}
	 
 	/**
     *	获得任务中的办理候选人
     */
	private Set<User> getTaskCandidate(String taskId) {
		Set<User> users = new HashSet<User>();
		List<IdentityLink> identityLinkList = taskService.getIdentityLinksForTask(taskId);
		if (identityLinkList != null && identityLinkList.size() > 0) {
			for (Iterator iterator = identityLinkList.iterator(); iterator
					.hasNext();) {
				IdentityLink identityLink = (IdentityLink) iterator.next();
				if (identityLink.getUserId() != null) {
					User user = getUser(identityLink.getUserId());
					if (user != null)
						users.add(user);
				}
				if (identityLink.getGroupId() != null) {
					// 根据组获得对应人员
					List<User> userList = identityService.createUserQuery()
							.memberOfGroup(identityLink.getGroupId()).list();
					if (userList != null && userList.size() > 0)
						users.addAll(userList);
				}
			}
 
		}
		return users;
	}
 
	private User getUser(String userId) {
		User user = (User) identityService.createUserQuery().userId(userId)
				.singleResult();
		return user;
	}

}
